package com.threegroup.admin.service;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.threegroup.admin.dao.ShoppingCartEntityDao;
import com.threegroup.admin.entity.ShoppingCartEntity;
import com.threegroup.common.utils.Result;
import com.threegroup.common.validator.AssertUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

@Service
public class ShoppingCartService {
    @Resource
    private ShoppingCartEntityDao shoppingCartEntityDao;

    /**
     * 删除
     * @param ids
     */
    public Result delete(Long[] ids) {
        AssertUtils.isNull(ids,"ids为空请重试");
        for (Long id : ids) {
            //判断该id是否存在
            AssertUtils.isTrue(null == shoppingCartEntityDao.selectByCartUserId(id), "请输入有效id！");
            int count = shoppingCartEntityDao.delete(id);
            //进行删除
            AssertUtils.isTrue(count<1,"删除失败！");
        }


        Result result=new Result<ShoppingCartEntity>();
        result.setMsg("删除成功！");
        result.setCode(0);
        return result;
    }

    /**
     * 分页
     */
    public Result<PageInfo<ShoppingCartEntity>> selectCartList(Integer limit1, Integer page1, String order1, String orderField1,String userId1) {
        Result<PageInfo<ShoppingCartEntity>> pageInfoResult = new Result<>();
        //校验参数
        Integer limit;
        Integer page;
        String order;
        String orderField;
        //校验
        limit = (limit1 != null) ? limit1 : 10;//默认10
        page = (page1 != null) ? page1 : 1;//默认第1页
        order = (StringUtils.isBlank(order1)) ? "asc" : order1;//默认
        orderField = (StringUtils.isBlank(orderField1)) ? "name" : orderField1;//默认排序字段
        //开启分页
        PageHelper.startPage(page,limit);

        if (userId1=="") {
            //获取list集合
            List<ShoppingCartEntity> shoppingCartEntityList =  shoppingCartEntityDao.queryAll(order,orderField);
            PageInfo<ShoppingCartEntity> shoppingCartEntityPageInfo = new PageInfo<ShoppingCartEntity>(shoppingCartEntityList);
            //设置值
            pageInfoResult.setData(shoppingCartEntityPageInfo);
        }else {
            Long userId=Long.valueOf(userId1);
            //获取list集合
            List<ShoppingCartEntity> shoppingCartEntityList =  shoppingCartEntityDao.selectByCartUserId(userId);
            PageInfo<ShoppingCartEntity> shoppingCartEntityPageInfo = new PageInfo<ShoppingCartEntity>(shoppingCartEntityList);
            //设置值
            pageInfoResult.setData(shoppingCartEntityPageInfo);
        }
        return pageInfoResult;
    }
}
